﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using ZilLion.Service.Core.Domain.EntityBase;
using ZilLion.Service.WeChatMall.Domain.Entitys.AppInfo;
using ZilLion.Service.WeChatMall.Domain.Repositorys.Interface;
using ZilLion.Service.WeChatMall.Domain.Requests;
using ZilLion.Service.WeChatMall.Domain.Responses;
using ZilLion.Service.WeChatMall.Domain.Responses.Appinfo;
using ZilLion.Service.WeChatMall.Domain.Services.Interface;

namespace ZilLion.Service.WeChatMallOss.Controllers
{
    /// <summary>
    ///     微商城后台微信app(商户信息)设置
    /// </summary>
    [Route("Api/WechatMallOss/App")]
    public class WeChatAppController : WechatMallOssControllerBase
    {
        private readonly IAppInfoService _appInfoService;
        private readonly IGdMapRepository _gdMapRepository;

        public WeChatAppController(IAppInfoService appInfoService, IGdMapRepository gdMapRepository)
        {
            _appInfoService = appInfoService;
            _gdMapRepository = gdMapRepository;
        }

        /// <summary>
        ///     获取当前客户名下所有微信APP
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [Route("GetApps")]
        [HttpGet]
        public AppInfoListResponse GetApps(string token = null)
        {
            var zlkey = GetZlCompanyKey();
            var dtos = _appInfoService.GetApps(zlkey);
            return new AppInfoListResponse {Appinfos = dtos};
        }

        /// <summary>
        ///     根据appid 获取APP信息
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [Route("GetAppByAppId")]
        [HttpGet]
        public AppInfoResponse GetAppByAppId(string appid, string token = null)
        {
            var dto = _appInfoService.GetAppByAppId(appid);

            return new AppInfoResponse {Appinfo = dto};
        }

        /// <summary>
        ///     保存app信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [Route("SaveAppInfo")]
        [HttpPost]
        public AppInfoResponse SaveAppInfo([FromBody] AppInfoRequest request, string token = null)
        {
            var pics = request.SwipePics.Aggregate(string.Empty, (current, swipePic) => current + swipePic + ",");
            if (pics.IsNotNullOrEmpty())
                pics = pics.Left(pics.Length - 1);

            var remarks = request.FixedRemarks.Aggregate(string.Empty, (current, remark) => current + remark + ",");
            if (remarks.IsNotNullOrEmpty())
                remarks = remarks.Left(remarks.Length - 1);

            var appBasicInfoEntity = new AppBasicInfoEntity
            {
                AppId = request.AppId,
                AppName = request.AppName,
                AppHomeType = request.AppHomeType,
                UpdatedTime = DateTime.Now.GetNowChinaTime(),
                MainShopid = request.MainShopid,
                SendRange = request.SendRange,
                SwipePics = pics,
                Updater = GetUserId(),
                ZlCompanyKey = GetZlCompanyKey(),
                CrmApiGetWay = request.CrmApiGetWay,
                CrmQrCodeUrl = request.CrmQrCodeUrl,
                CityAdcode = request.CityAdcode,
                CityName = request.CityName,
                CityCenter = request.CityCenter,
                FixedRemarks = remarks
            };

            var rainfo = new AppRaInfoEntity
            {
                AppId = request.AppId,
                MaxOrderPayMy = request.MaxOrderPayMy,
                UpdatedTime = DateTime.Now.GetNowChinaTime(),
                Updater = GetUserId()
            };


            return new AppInfoResponse
            {
                Appinfo = _appInfoService.SaveAppInfo(new AppInfoDto
                {
                    AppRaInfo = rainfo,
                    AppBasicInfo = appBasicInfoEntity
                })
            };
        }

        /// <summary>
        ///     获取客户端IP和地址信息
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [Route("GetAllCitys")]
        [HttpGet]
        public MapCitysResponse GetAllCitys(string token = null)
        {
            var result = new MapCitysResponse {MapCategorys = new List<MapCategoryDto>()};
            var dtos = _gdMapRepository.GetAllCitys();
            //
            if (dtos.Status == "1")
            {
                var provinces = dtos?.Subdistricts?.FirstOrDefault()?.Subdistricts;
                var order = 1;
                foreach (var province in provinces ?? new List<MapDistrict>())
                {
                    var wechatMallCategoryDto = new MapCategoryDto {Name = province.Name, Order = order};
                    var list = new List<MapDistrict>();
                    foreach (var city in province.Subdistricts)
                        list.Add(city);
                    wechatMallCategoryDto.Citys = list;
                    result.MapCategorys.Add(wechatMallCategoryDto);
                    order++;
                }
            }
            return result;
        }

        /// <summary>
        ///     删除app信息
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        [Route("deleteApp")]
        [HttpDelete]
        public ResponseBase DeleteApp(string appid, string token = null)
        {
            _appInfoService.DeleteApp(appid);
            return new ResponseBase();
        }


        /// <summary>
        ///     删除app信息
        /// </summary>
        /// <returns></returns>
        [Route("SaveAppGsRelationShip")]
        [HttpPost]
        public ResponseBase SaveAppGsRelationShip([FromBody]AppGsRelationShipRequest request, string token = null)
        {
            var relationList = new List<AppGsRelationShipEntity>();
            foreach (var gsid in request.Gsids)
            {
                var entity = new AppGsRelationShipEntity
                {
                    AppId = request.Appid,
                    GsId = gsid,
                    Updater = GetUserId(),
                    UpdatedTime = DateTime.Now.GetNowChinaTime()
                };
                relationList.Add(entity);
            }


            _appInfoService.SaveAppGsRelationShip(relationList);
            return new ResponseBase();
        }

        /// <summary>
        ///     检查crm 和appid 是否合法
        /// </summary>
        /// <param name="crmurl"></param>
        /// <param name="token"></param>
        /// <param name="appid"></param>
        /// <returns></returns>
        [Route("CheckAppIdValid")]
        [HttpGet]
        public CheckAppIdValidResponse CheckAppIdValid(string appid, string crmurl, string token = null)
        {
            var appIsValid = _appInfoService.CheckAppIdValid(appid, crmurl);
            return new CheckAppIdValidResponse {IsValid = appIsValid};
        }
    }
}